package com.codechuan.didi_web.utils;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import okhttp3.Authenticator;

import java.io.IOException;
import java.net.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;

import static com.codechuan.didi_web.service.impl.ThreadManagerServiceImpl.getRandomAlphanumeric;
import static com.codechuan.didi_web.thread.GetAnOrderThread.getMD5;

public class TestProxyOKHttpClient {
    private static final String secretId = "otdn4vnfgj5wacvvvokl";
    private static final String signature = "702hr511l1gn51kzphaxhx0sicvncw31";
    private static final String urlString = "https://dps.kdlapi.com/api/getdps/?secret_id=" + secretId + "&signature=" + signature + "&num=1&pt=1&format=text&sep=1";

    public static void main(String args[]) throws IOException {
        // 目标网站
        String targetUrl = "https://dev.kdlapi.com/testproxy";

        // 用户名密码认证(私密代理/独享代理)
        final String username = "d1665828463";
        final String password = "2p4n0ufj";

        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        // 读取响应
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            String[] parts = response.toString().split(":");
            if (parts.length >= 2) {
                String ip = parts[0].trim();
                int port = Integer.parseInt(parts[1].trim());

                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip, port));

                Authenticator authenticator = new Authenticator() {
                    @Override
                    public Request authenticate(Route route, Response response) throws IOException {
                        String credential = Credentials.basic(username, password);
                        return response.request().newBuilder()
                                .header("Proxy-Authorization", credential)
                                .build();
                    }
                };
                OkHttpClient client = new OkHttpClient.Builder()
                        .proxy(proxy)
                        .proxyAuthenticator(authenticator)
                        .build();

                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("api_version", "1.0.1");
                hashMap.put("appid", 35009);
                hashMap.put("role", 1);
                hashMap.put("extra_info", "{\"channel\":1100000004}");
                hashMap.put("device_name", "Pixel 3");
                String name = "Ny3d38n" + getRandomAlphanumeric(6) + "UVdBHzEB2HLTUdH8Sl661KCqZvgeewleJZUedUiuxPw98IptM";
                hashMap.put("sec_session_id", name);
                hashMap.put("policy_name_list", new ArrayList<>());
                hashMap.put("ddfp", UUID.randomUUID().toString().replaceAll("", ""));
                hashMap.put("lang", "zh-CN");
                hashMap.put("wsgenv", "");
                hashMap.put("cell", "19881556793");
                hashMap.put("country_calling_code", "+86");
                hashMap.put("code_type", 0);
                hashMap.put("scene", 1);
                String jsonString = JSONObject.toJSONString(hashMap);
                String encode = URLEncoder.encode(jsonString);
                String param = "lang=zh-CN&token=&access_key_id=9&appversion=6.8.50&channel=1100000004&_ds=&xpsid=4ed3890f8b759bd7a02bf1f05f603f4b&xpsid_root=4ed3890f8b759bd7a02bf1f05f603f4b&q="
                        + encode;
                String requestData = param;
                MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
                RequestBody body = RequestBody.create(mediaType, requestData);
                Request request = new Request.Builder()
                        .url(targetUrl)
                        .url("https://epassport.diditaxi.com.cn/passport/login/v5/codeMT?&wsgsig=dd04-opzKIpzv0Helcs8AzeS%2Bt8xv2y9PNdtJ8dTgXCZVc7FBaXDBgRC4W03Plxr%2BQO1c4Kfe0G3mkAAcKH0R%2BgsjrtpZG7%2FQbBGxuzosZsf%2B0iA%2BQVpk5QIdXj6Xe7ArNHch63TcZt3nd9SXNV1a3X7ADt011vcy")
                        .addHeader("Host", "epassport.diditaxi.com.cn")
                        .addHeader("secdd-authentication", "")
                        .addHeader("charset", "utf-8")
                        .addHeader("mpxlogin-ver", "5.4.30")
                        .addHeader("didi-header-rid", getMD5(String.valueOf(Instant.now().toEpochMilli())))
                        .addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 12; Pixel 3 Build/SP1A.210812.016.C2; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/122.0.6261.120 Mobile Safari/537.36 XWEB/1220067 MMWEBSDK/20240404 MMWEBID/3880 MicroMessenger/8.0.49.2600(0x28003156) WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64 MiniProgramEnv/android")
                        .addHeader("content-type", "application/x-www-form-urlencoded")
                        .addHeader("secdd-challenge", "3|v1.1.0||||||")
                        .addHeader("didi-header-hint-content", "{\"lang\":\"zh-CN\",\"Cityid\":\"\"}")
                        .addHeader("Referer", "https://servicewechat.com/wxaf35009675aa0b2a/866/page-frame.html")
                        .post(body)
                        .build();

                Response i_response = client.newCall(request).execute();
                System.out.println(i_response.body().string());
            }
        } else {
            System.out.println("GET request not worked");
        }
        connection.disconnect();
    }
}